package userpass

import (
	"fmt"
	"gitee.com/jiangjiali/vault/api"
	"os"
	"strings"

	"gitee.com/jiangjiali/vault/sdk/helper/mitchellh/mapstructure"
	pwd "gitee.com/jiangjiali/vault/sdk/helper/password"
)

type CLIHandler struct {
	DefaultMount string
}

func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) {
	var data struct {
		Username string `mapstructure:"username"`
		Password string `mapstructure:"password"`
		Mount    string `mapstructure:"mount"`
		Method   string `mapstructure:"method"`
		Passcode string `mapstructure:"passcode"`
	}
	if err := mapstructure.WeakDecode(m, &data); err != nil {
		return nil, err
	}

	if data.Username == "" {
		return nil, fmt.Errorf("'username' must be specified")
	}
	if data.Password == "" {
		fmt.Fprintf(os.Stderr, "Password (will be hidden): ")
		password, err := pwd.Read(os.Stdin)
		fmt.Fprintf(os.Stderr, "\n")
		if err != nil {
			return nil, err
		}
		data.Password = password
	}
	if data.Mount == "" {
		data.Mount = h.DefaultMount
	}

	options := map[string]interface{}{
		"password": data.Password,
	}
	if data.Method != "" {
		options["method"] = data.Method
	}
	if data.Passcode != "" {
		options["passcode"] = data.Passcode
	}

	path := fmt.Sprintf("auth/%s/login/%s", data.Mount, data.Username)
	secret, err := c.Logical().Write(path, options)
	if err != nil {
		return nil, err
	}
	if secret == nil {
		return nil, fmt.Errorf("empty response from credential provider")
	}

	return secret, nil
}

func (h *CLIHandler) Help() string {
	help := `
使用: vault login -method=userpass [配置 K=V...]

  userpass auth方法允许用户使用内部用户数据库进行身份验证。

  如果启用了MFA，则可能需要“method”和/或“passcode”，具体取决于MFA方法。
  要检查正在使用的MFA，请运行：

      $ vault read auth/<mount>/mfa_config

  认证为“sally”:

      $ vault login -method=userpass username=sally
      Password (will be hidden):

  身份验证为“bob”:

      $ vault login -method=userpass username=bob password=password

配置:

  method=<string>
      MFA method.

  passcode=<string>
      MFA OTP/passcode.

  password=<string>
      用于身份验证的密码。如果未提供，CLI将在stdin上提示。

  username=<string>
      用于身份验证的用户名。
`

	return strings.TrimSpace(help)
}
